/**
 * Node.js 遍历 step 目录，去生成 html。
 * --------------------------------
 * 命令：
 * node learn-vue3-js/auto-html.js
 * --------------------------------
 * 环境：IsDev
 * IsDev = true: 线上路径
 * IsDev = false: 本地电脑路径
 */
const fs = require('fs')
const os = require('os')
const path = require('path')

const RootPath = path.join(__dirname)
const RootHtml = path.join(__dirname, 'index.html')
const IsDev = true
// const IsDev = false
const ProdName = 'lear-vue3-js'
// const ProdName = 'tree/master/lear-vue3-js'

function exits(filePath) {
  if (!filePath) return -1
  fs.stat(filePath, (exitErr, stats) => {
    if (exitErr) return -1
    if (stats.isDirectory()) {
      return 0
    } else {
      return 1
    }
  })
}

function fsRemoveFile(filePath) {
  fs.unlinkSync(filePath)
}

function fsRemoveDir(dirPath) {
  fs.rmdirSync(dirPath)
}

function rmRootHtml() {
  const stats = exits(RootHtml)
  if (stats === 1) {
    fsRemoveFile(RootHtml)
  } else if (stats === 0) {
    fsRemoveDir(RootHtml)
  }
}

/**
 * 下面是 自动读取文件目录，并写入文件
 * -----------------------------
 * 结合我以前写的:
 * 一、docs vuepress api
 * https://gitee.com/srxboys/docs-vuepress-api
 *
 * 二、node-express-api-server
 * https://gitee.com/cheere/node-express-api-server
 */

function readDirName(dirNamePath) {
  // console.log('文件名 dirNamePath=', dirNamePath)
  if (!dirNamePath) return ''
  let name = fs.readFileSync(dirNamePath, 'utf-8');
  name = trimStr(name)
  return name
}

function trimStr(str) {
  if (!str) return ''
  return str.replace(/(^\s*)|(\s*$)/g,"");
}

const excludes = ['.DS_Store']
const DirTitleName = '.name'

function lookDir(dirPath, result = [], filePath, depth = 0) {
  const children = {};
  const fsReadPath = path.join(dirPath, filePath)
  fs.readdirSync(fsReadPath).forEach(file => {
    const fullpath = path.join(fsReadPath, file)
    // console.log('\rfullpath=', fullpath)
    // console.log('\depth=', depth)
    const fileinfo = fs.statSync(fullpath)
    if (excludes.indexOf(file) < 0) {
      if (fileinfo.isFile()) {
        if(file === DirTitleName) {
          children.desc = readDirName(fullpath)
        } else if (file === 'index.html') {
          if (IsDev) {
            children.path = fullpath
          } else {
            children.path = path.join(ProdName, filePath, file)
          }
        }
      } else if (fileinfo.isDirectory()) {
        if (depth === 0) {
          const newFilePath = path.join(filePath, file)
          // console.log('newFilePath=', newFilePath)
          const childrenObj = lookDir(dirPath, result, newFilePath, depth + 1)
          childrenObj.name = file
          result.push(childrenObj)
        }
      }
    }
  })
  return children
}

const HtmlHeader = `
<!-- 该页面是动态生成的，不要在源代码里面编辑 -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>learn-vue3-js - root</title>
  <script src="./js/vue.js"></script>
  <style>
    .blue {
      color: blue
    }

    .sub {
      color: purple
    }
  </style>
</head>
<body>
  <h1>学习Vue3</h1>
  <p>html + js + vue.js</p>
  <hr>
  <br>
`

const HtmlFooter = `
</body>
</html>
`

function writeRootHtml() {
  const targetPath = RootHtml

  const logDev = IsDev ? '测试' : '线上'
  const logData = '<!-- 当前环境：' + logDev + '-->' + lineBreak + lineBreak
  write(targetPath, logData)

  addWrite(targetPath, HtmlHeader + lineBreak)

  // 遍历目录
  const filePath = 'step'
  let result = []
  lookDir(RootPath, result, filePath)
  // console.log('result=', result)
  const len = result.length || 0
  for (let i = 0; i < len; i++) {
    const item = result[i]
    const name = item.name || ''
    const desc = item.desc || ''
    const namePath = item.path || ''
    const data = '  ' + '<div>' + name + ' - ' + '<a class="blue" target="_blank" href="' + namePath + '">' + desc + '</a> </div> <br> <br>' + lineBreak + lineBreak
    addWrite(targetPath, data)
  }

  addWrite(targetPath, HtmlFooter)
}

const lineBreak = os.EOL
const MODE_0666 = parseInt('0666', 8)
// const MODE_0755 = parseInt('0755', 8)

function write(file, str, mode) {
  fs.writeFileSync(file, str, { mode: mode || MODE_0666 })
  // console.log('   \x1b[36mcreate\x1b[0m : ' + file)
}

function addWrite(file, str, mode) {
  fs.appendFileSync(file, str, { mode: mode || MODE_0666 })
  // console.log('   \x1b[36mcreate\x1b[0m : ' + file)
}

rmRootHtml()
writeRootHtml()